package com.uzai.console.service.tb.tbpunishorder.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.merbaseconfig.MerBaseConfigQuery;
import com.uzai.console.dto.tb.tbpunishorder.*;
import com.uzai.console.entity.FdFollowGroup;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.TbPunishOrder;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.mapper.TbPunishOrderMapper;
import com.uzai.console.service.fd.FdFollowGroupService;
import com.uzai.console.service.ratelimit.RatelimitService;
import com.uzai.console.service.tb.tbpunishorder.TbPunishOrderSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 淘宝处罚订单线程
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class TbPunishOrderSyncServiceImpl implements TbPunishOrderSyncService {

    Logger logger = LoggerFactory.getLogger(TbPunishOrderSyncServiceImpl.class);

    @Autowired
    private TbPunishOrderServiceImpl tbPunishOrderService;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbPunishOrderMapper tbPunishOrderMapper;
    @Autowired
    private FdFollowGroupService fdFollowGroupService;

    /**
     * 批量扣款淘宝处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbPunishOrderIdListDto
     * @return null
     */
    public void batchTakeOffTbPunishOrder(TbPunishOrderIdListDto tbPunishOrderIdListDto){

        List<Long> idList = tbPunishOrderIdListDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择需要扣款的订单id");
        }
        for(Long id : idList){
            try{
                TbPunishOrderIdDto tbPunishOrderIdDto = new TbPunishOrderIdDto();
                BeanUtils.copyProperties(tbPunishOrderIdListDto, tbPunishOrderIdDto);
                tbPunishOrderIdDto.setMerId(tbPunishOrderIdListDto.getMerId());
                tbPunishOrderIdDto.setId(id);
                tbPunishOrderService.takeOffTbPunishOrder(tbPunishOrderIdDto);
            }catch (Exception e){
                logger.error("------批量扣款淘宝订单异常，id={}, msg={}",id, e.getMessage());
            }
        }
    }


    /**
     * 异步自动扣款淘宝处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void autoChargebackHanderSync(){

        //限流key
        String taskLimitKet = "-autoChargebackHanderSync-taskLimitKey-";
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if(object != null){
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        logger.info("-----调用异步自动扣款淘宝处罚订单线程--xxlJob start--");

        MerBaseConfigQuery merBaseConfigQuery = new MerBaseConfigQuery();
        merBaseConfigQuery.setKey(MerConfigKeyEnum.TB_PUNISH_ORDER_AUTO_CHARGEBACK.getValue());
        //查询所有的支付宝支付记录
        Page<MerBaseConfig> page_merBaseConfig = new Page<>();
        page_merBaseConfig.setCurrent(1);//只查第一页
        page_merBaseConfig.setSize(10); //每页查询10个
        page_merBaseConfig.addOrder(OrderItem.asc("id"));//默认id升序
        Long idStart_merBaseConfig = 0L;
        List<MerBaseConfig> merBaseConfigList = merBaseConfigMapper.findByList(page_merBaseConfig, merBaseConfigQuery);
        while (merBaseConfigList != null && merBaseConfigList.size() > 0){
            for (MerBaseConfig merBaseConfig : merBaseConfigList){
                if(merBaseConfig.getId().longValue() > idStart_merBaseConfig.longValue()){
                    idStart_merBaseConfig = merBaseConfig.getId();
                }
                if(Integer.valueOf(merBaseConfig.getVal()).intValue() == 1){//开启自动扣费
                    //限流判断
                    String key = "TbPunishOrderAutoChargeback-" + merBaseConfig.getMerId();
                    boolean inRateLimit = ratelimitService.inRateLimit(key,1,60);
                    if (!inRateLimit){
                        continue;
                    }

                    //查询此运营商的所有处罚订单，自动进行扣款处理
                    TbPunishOrderQuery tbPunishOrderQuery = new TbPunishOrderQuery();
                    tbPunishOrderQuery.setMerId(merBaseConfig.getMerId());
                    tbPunishOrderQuery.setStatus(0);//未处理
                    tbPunishOrderQuery.setQueryStartTime(1673712000); //从2023-01-15 00:00:00分开始之后的处罚订单才自动扣款
                    //查询所有的支付宝支付记录
                    Page<TbPunishOrder> page_tbPunishOrder = new Page<>();
                    page_tbPunishOrder.setCurrent(1);//只查第一页
                    page_tbPunishOrder.setSize(10); //每页查询10个
                    page_tbPunishOrder.addOrder(OrderItem.asc("id"));//默认id升序
                    Long idStart_tbPunishOrder = 0L;
                    List<TbPunishOrder> tbPunishOrderList = tbPunishOrderMapper.findByList(page_tbPunishOrder, tbPunishOrderQuery);
                    while (tbPunishOrderList != null && tbPunishOrderList.size() > 0) {
                        for (TbPunishOrder tbPunishOrder : tbPunishOrderList) {
                            if (tbPunishOrder.getId().longValue() > idStart_tbPunishOrder.longValue()) {
                                idStart_tbPunishOrder = tbPunishOrder.getId();
                            }
                            if(tbPunishOrder.getStatus() == 0){//未处理的订单进行自动扣款
                                TbPunishOrderIdDto tbPunishOrderIdDt = new TbPunishOrderIdDto();
                                tbPunishOrderIdDt.setMerId(merBaseConfig.getMerId());
                                tbPunishOrderIdDt.setId(tbPunishOrder.getId());
                                try {
                                    tbPunishOrderService.takeOffTbPunishOrder(tbPunishOrderIdDt);
                                }catch (Exception e){
                                    logger.error("----自动处理处罚订单出错--,msg={}", e.getMessage());
                                }
                            }
                        }
                        //执行下一次查询
                        tbPunishOrderQuery.setIdStart(idStart_tbPunishOrder);
                        tbPunishOrderList = tbPunishOrderMapper.findByList(page_tbPunishOrder, tbPunishOrderQuery);
                    }

                    //执行完成，删除限流标志
                    redisTemplate.delete(key);
                }
            }

            merBaseConfigQuery.setIdStart(idStart_merBaseConfig);
            merBaseConfigList = merBaseConfigMapper.findByList(page_merBaseConfig, merBaseConfigQuery);
        }

        //删除限流key
        redisTemplate.delete(taskLimitKet);
    }


    /**
     * 异步删除3个月(90天)之前的淘宝处罚订单
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    @Async("taskExecutor")
    @Override
    public void deleteTbPunishOrderHistorySync() {
        int deleteDay = DateUtil.getNowTime() - 24*3600*90;
        tbPunishOrderMapper.deleteBeforeDay(deleteDay, null);
    }

    /**
     * 异步删除7天之前的发单官方采集群历史消息
     * @author jitwxs
     * @date 2022/1/16 17:16
     */
    @Async("taskExecutor")
    @Override
    public void deleteFdFollowGroupMsgHistorySync(){
        int deleteDay = DateUtil.getNowTime() - 24*3600*7;
        fdFollowGroupService.deleteFdFollowGroupMsgHistoryBeforeDay(deleteDay);
    }

}
